package com.gxa.login.service.impl;

import com.netflix.client.http.HttpRequest;
import param.AuthParam;
import param.LoginParam;
import com.gxa.login.dao.MemberDao;
import com.gxa.login.dao.RoleDao;
import com.gxa.login.service.LoginService;
import com.gxa.login.util.JwtUtil;
import com.gxa.login.validator.MyValidator;
import dto.ResultDTO;
import entity.Auth;
import entity.Member;
import entity.Role;
import group.Email;
import group.Phone;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.Response;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private MyValidator myValidator;

    @Resource
    private MemberDao memberDao;

    @Resource
    private RoleDao roleDao;

    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RocketMQTemplate rocketMQTemplate;
    /**
     * 邮箱登录
     * @param member
     * @return
     */
    @Override
    public ResultDTO loginByEmail(Member member) {
        myValidator.validate(member, Email.class);
        Member dbMember = memberDao.queryByEmail(member.getMemberEmail());
        if(dbMember == null){
            return Response.error(1001,"没有该用户");
        }
        if(redisTemplate.hasKey("token:"+dbMember.getMemberId())){
            redisTemplate.delete("token:"+dbMember.getMemberId());
        }
        String token = JwtUtil.sign("token", dbMember.getMemberId());
        LoginParam loginParam = getAuths(dbMember);
        loginParam.setMember(dbMember);
        loginParam.setToken(token);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = simpleDateFormat.format(new Date());
        loginParam.setCreateTime(format);
        loginParam.setIndate("3");
        redisTemplate.opsForHash().put("token:"+dbMember.getMemberId(),token,loginParam.getAuthList());
        return Response.success(200,"登录成功",loginParam);
    }

    /**
     * 手机号登录
     * @param member
     * @return
     */
    @Override
    public ResultDTO loginByPhone(Member member) {
        myValidator.validate(member, Phone.class);
        Member dbMember = memberDao.queryByPhone(member.getMemberPhone());
        if(dbMember == null){
            return Response.error(1001,"没有该用户");
        }
        if(!redisTemplate.hasKey("smsCode:" + member.getMemberPhone())){
            return Response.error(1003,"验证码已过期");
        }
        Object o = redisTemplate.opsForSet().pop("smsCode:" + member.getMemberPhone());
        if(!member.getCode().equals(o.toString())){
            return Response.error(1002,"验证码正确");
        }
        String token = JwtUtil.sign("token", dbMember.getMemberId());
        LoginParam loginParam = getAuths(dbMember);
        loginParam.setMember(dbMember);
        loginParam.setToken(token);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = simpleDateFormat.format(new Date());
        loginParam.setCreateTime(format);
        loginParam.setIndate("3");
        redisTemplate.opsForHash().put("token:"+dbMember.getMemberId(),token,loginParam.getAuthList());
        return Response.success(200,"登录成功",loginParam);
    }

    /**
     * 发短信
     */
    @Override
    public ResultDTO sendCode(Member member){
        if (!redisTemplate.hasKey("isCode")) {
            redisTemplate.opsForSet().add("isCode","1");
            redisTemplate.expire("isCode", 60, TimeUnit.SECONDS);
            // 发消息
            rocketMQTemplate.convertAndSend("phone-code", member.getMemberPhone());
            return Response.success(200,"发送成功");
        }
        return Response.success(1001,"短信发送频繁");


    }
    /**
     * 拿到权限
     * @param dbMember
     * @return
     */
    private LoginParam getAuths(Member dbMember){

        Role role = roleDao.queryById(dbMember.getRoleId());
        ArrayList<Auth> menuList = new ArrayList<>();
        ArrayList<String> authList = new ArrayList<>();
        for (Auth auth : role.getAuths()) {
            if(auth.getIsMenu() == 1){
                menuList.add(auth);
            }else {
                authList.add(auth.getAuthUrl());
            }
        }
        LoginParam loginParam = new LoginParam();
        loginParam.setAuthList(authList);
        loginParam.setMenuList(menuList);
        return loginParam;
    }

    @Override
    public ResultDTO logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(token == null){
            return new ResultDTO(1001,"头部没有token");
        }
        Integer userId = JwtUtil.getUserId(token);
        redisTemplate.opsForHash().delete("token:"+userId,token);
        return new ResultDTO(200,"退出成功");
    }
}
